<template>
  <div>
    <StepProgress :step-index="1"/>
    <div>
      <el-form label-position="right" :model="userForm" :rules="userRules" status-icon ref="userForm"
               label-width="100px" class="demo-ruleForm">
        <el-form-item label="app id" prop="appId">
          <el-input type="text" v-model="userForm.appId" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="app secret" prop="appSecret">
          <el-input type="password" @blur="getToken" v-model="userForm.appSecret" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="redirectUrl" prop="redirectUrl">
          <el-input type="text" v-model="userForm.redirectUrl" readonly autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="state" prop="state">
          <el-input type="text" v-model="userForm.state" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('userForm')" :disabled="canSubmit">确认信息</el-button>
          <el-button type="danger" @click="resetForm('userForm')">重置信息</el-button>
        </el-form-item>
      </el-form>
      <el-dialog
          title="提示"
          v-model="isSuccess"
          width="30%"
          :before-close="handleClose">
        <span>前往授权</span>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="isSuccess = false">取 消</el-button>
            <el-button type="primary" @click="openNewWindow">确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <el-button type="primary" @click="goToNext">下一步</el-button>
    </div>
  </div>
</template>

<script>
import StepProgress from '@/components/StepProgress';
import uuid from 'node-uuid';
import Cookies from 'js-cookie';
import {getAppToken} from '@/api/auth/auth';
import lark from '@/config';

export default {
  name: 'userInfo',
  components: {StepProgress},
  data() {
    return {
      userForm: {
        appId: '',
        appSecret: '',
        state: '',
        redirectUrl: lark.env.redirect_url,
      },
      stateForm: {
        p1: '12',
        uuid: '',
      },
      dialogFormVisible: false,
      userRules: {
        appId: [
          {required: true, message: '请输入app id', trigger: 'blur'},
          {min: 20, max: 20, message: '输入的app id 不合法，请检查是否正确', trigger: 'blur'},
        ],
        appSecret: [
          {required: true, message: '请输入app secret', trigger: 'blur'},
          {min: 32, max: 32, message: '输入的app secret 不合法，请检查是否正确', trigger: 'blur'},
        ],
        redirectUrl: [
          {required: true, message: '请输入在开发者后台设置的 「重定向URL」链接', trigger: 'blur'},
        ],
      },
      canSubmit: false,
      template: '',
      isSuccess: false,
    };
  },
  created() {
    const {appId, appSecret} = this.$store.getters.getAppInfo;
    this.userForm.appId = appId;
    this.userForm.appSecret = appSecret;
    const {uuid, expires_in} = this.$route.query;
    if (uuid && expires_in) {
      // 恢复表单
      this.userForm = JSON.parse(localStorage.getItem('userForm'));
      this.$message.success('已成功获取用户信息！');
      Cookies.set('uuid', uuid, {expires: 1/12});
      this.canSubmit = true;
    }
  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then((_) => {
            done();
          })
          .catch((_) => {
          });
    },
    async getToken() {
      // 1、提交验证成功后，把信息取hash存到cookie
      const {appId, appSecret} = this.userForm;
      this.$utils.genAppInfo(appId, appSecret);
      const content = await getAppToken(appId, appSecret);
      console.log(content);
      const {data} = content;
      if (data.code === 0) {
        this.$message.success('已成功上传应用信息！请勿重复操作');
        this.$utils.genAppInfo(appId, appSecret);
      } else {
        this.$message.error('未知原因');
      }
    },
    genRedirectUrl() {
      if (this.template.length === 0) {
        let url = this.userForm.redirectUrl;
        if (url.includes(' ')) {
          this.$message.error('检测到 redirect url 存在空格，已为您去除！');
          url = url.trim();
        }
        url = encodeURIComponent(url);
        this.stateForm.uuid = uuid.v1();
        const stateParams = {
          app_id: this.userForm.appId,
          location: window.location.href,
          uuid: this.stateForm.uuid, // 本次验证的唯一标识
        };
        const myState = Buffer.from(JSON.stringify(stateParams), 'utf-8').toString('base64');
        this.template = `https://${lark.env.baseURL}/open-apis/authen/v1/index?redirect_uri=${url}&app_id=${this.userForm.appId}&state=${myState}`;
      }
      this.isSuccess = true;
    },
    saveForm() {
      const obj = {...this.userForm};
      localStorage.setItem('userForm', JSON.stringify(obj));
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$message.error('请检查表单项！');
          return false;
        }
        this.genRedirectUrl();
        this.$utils.genAppInfo(this.userForm.appId, this.userForm.appSecret);
        this.saveForm();
      });
    },
    resetForm(formName) {
      this.userForm = {
        appId: '',
        state: 'notEmpty',
        redirectUrl: '',
      };
      this.$refs[formName].resetFields();
      this.$message.success('成功清空信息');
      this.canSubmit = false;
    },
    goToNext() {
      const uuid = Cookies.get('uuid');
      if (uuid === undefined) {
        if (!this.canSubmit) {
          this.$message.warning('必须先确认信息才能进行下一步！');
          return;
        }
      } else {
        this.$message.success('已完整认证，无需再次认证');
      }
      this.$router.push({
        path: `/docs/docList`,
        query: {
          type: 'user',
        },
      });
    },
    openNewWindow() {
      window.open(this.template);
      this.isSuccess = false;
    },
  },
};
</script>

<style scoped>
.redirectUrl {
  font-size: 20px;
  word-break: break-all;
  white-space: normal;
}
</style>
